<template>
    <Dialog :app-dialog="appDialog">
        <div class="create-text">
            <template v-if="!isNewWord">
                <div>一、请根据模板内容进行填写，<el-button type="text" @click="downTemplate">下载模板</el-button></div>
                <div class="textWord">
                    <span> 二、请上传填写好的模板，以便导入文本，</span>
                    <el-form v-if="!isNewWord" ref="formRef" class="export" :model="form" :rules="rules">
                        <el-upload
                            action=""
                            accept=".xls,.xlsx"
                            :show-file-list="false"
                            :before-upload="onBeforeUpload"
                            :http-request="onHttpRequest"
                            class="file">
                            <el-link type="primary" :underline="false">&ensp;上传模板</el-link>
                        </el-upload>
                    </el-form>
                </div>
                <div v-if="form.files" class="file_info">
                    <el-icon><Document /></el-icon>
                    <div class="text">{{ form.files?.name }}</div>
                    <el-icon class="del_icon" @click="onRemoveFile"><circle-close /></el-icon>
                </div>
            </template>
            <el-form ref="formRef" :model="form" :rules="rules" :label-width="isNewWord ? '90px' : '40px'">
                <template v-if="isNewWord">
                    <el-form-item label="分组">
                        <el-cascader
                            ref="cascaderRef"
                            v-model="form.group"
                            style="width: 100%"
                            :options="groupData"
                            :props="defaultProps"
                            placeholder="请选择分组"
                            @change="orgChange" />
                    </el-form-item>
                    <el-form-item label="标题" prop="title">
                        <el-input v-model="form.title" placeholder="请输入文本标题" show-word-limit maxlength="12" />
                    </el-form-item>
                    <el-form-item label="内容" prop="con">
                        <el-input
                            v-model="form.con"
                            :rows="2"
                            type="textarea"
                            placeholder="请输入文本内容"
                            show-word-limit
                            maxlength="1000" />
                    </el-form-item>
                </template>
                <el-form-item v-if="isShowTag && !isNewWord" label="标签">
                    <el-scrollbar v-if="form.tags.length > 0" class="zw_scroll">
                        <div class="zw-el-tags">
                            <el-tag
                                v-for="tag in form.tags"
                                :key="tag.id"
                                closable
                                :disable-transitions="false"
                                @close="handleClose(tag.id)">
                                {{ tag.name }}
                            </el-tag>
                        </div>
                    </el-scrollbar>
                    <el-button @click="openTag">请选择标签</el-button>
                </el-form-item>
                <el-form-item v-if="isNewWord">
                    <template #label>
                        <div class="label_text">
                            <span>素材标签</span>
                            <el-tooltip :content="tagTips.materialTagTips" placement="top">
                                <img src="@/assets/image/material/question.png" alt="" />
                            </el-tooltip>
                        </div>
                    </template>
                    <selectTags ref="tagIdsRef" v-model="form.tag_ids" />
                </el-form-item>
            </el-form>
        </div>
    </Dialog>
    <!-- 标签弹框 -->
    <ZWSelectTag ref="wordSelectRef" @submit="getTags" />
</template>
<script setup lang="ts">
import { ref, reactive, watch, computed } from 'vue';
import Dialog from '@/components/Dialog.vue';
import ZWSelectTag from '@/components/ZWSelectTag.vue';
import selectTags from '@/view/content/components/selectTags.vue';
import { ElForm, ElMessage } from 'element-plus';
import domain from '@/utils/domain';
import { getGroupList, createText, EidtText, downTemp, importWord } from '@/api/concreation';
import { useStore } from '@/store';
import { endLoading, startLoading } from '@/utils/request';
import { getSetionId } from '@/utils/utils';
const store = useStore();
const formRef = ref<InstanceType<typeof ElForm>>();
const cascaderRef: any = ref(null); // 选择分组ref
const emit = defineEmits(['submit', 'groupIdChange']);
const props = defineProps(['groupId', 'type']);
const wordSelectRef = ref(null);
const wordVisible = ref(false);
const tags = computed(() => {
    return store.getters['content/tagsInfo'].tags;
});
const isEdit = ref(false);
const apiText = ref('');
const isShowTag = ref(true);
const tagTips = {
    materialTagTips: '该素材会被打上此素材标签，在列表上会展示',
    browseCustTips: '浏览该素材的客户将被打上此客户标签',
    shareCustTips: '点击该素材的分享按钮并生成分享链接的客户将被打上此客户标签'
};
const tagIdsRef = ref(null);
//编辑Id
const editInfo = ref({});
// 分组列表
// 是否是新建话术
const isNewWord = computed(() => {
    return store.getters['content/isNewWord'];
});
const defaultProps = {
    checkStrictly: true,
    emitPath: false,
    label: 'name',
    value: 'id'
};

// 分组 tree
const groupData = ref([]);

/**
 * @description: 获取分组数据
 * @return {*}
 */
const getGroupListFunc = async () => {
    const res = await getGroupList({ type: props.type });
    groupData.value = res.data;
};
// 取消
const cancelHandel = () => {
    form.files = null;
    form.group = '';
    form.title = '';
    form.con = '';
    form.tags = [];
    form.tag_ids = [];
    store.commit('content/WORD_ART_DIALOG', false);
    setTimeout(() => {
        isEdit.value = false;
        store.dispatch('content/isNewWord', true);
    }, 500);
    // appDialog.visible = false
    wordVisible.value = false;
    formRef.value.resetFields();
};
//确定上传
const submitHandel = () => {
    startLoading();
    try {
        if (isShowTag.value) {
            formRef.value.validate(async (valid: any) => {
                if (valid) {
                    const groupId = form.group;
                    try {
                        const arr: any[] = [];
                        form.tags.forEach((item: any) => {
                            arr.push(item.id);
                        });
                        // 导入模板
                        if (!isNewWord.value) {
                            const formData = new FormData();
                            formData.append('text_import', form.files);
                            formData.append(`tag_ids`, arr);
                            try {
                                const result: any = await importWord(formData);
                                ElMessage.success('导入话术成功');
                            } catch (e) {
                                // 导入文件服务端报错时停止执行，展示错误信息并停止 londing
                                endLoading();
                                return;
                            }
                        } else {
                            const params = {
                                title: form.title,
                                group_id: form.group,
                                content: form.con,
                                tag_ids: getSetionId('id', form.tag_ids)
                            };
                            isEdit.value
                                ? Object.assign(params, {
                                      media_content_id: editInfo.value.id
                                  })
                                : ''; // 修改文本
                            // 创建文本
                            isEdit.value ? await EidtText(params) : await createText(params);

                            ElMessage.success(`${!isEdit.value ? '新建' : '修改'}话术成功`);
                        }
                        cancelHandel();
                        emit('submit', { refresh: true });
                        emit('groupIdChange', groupId);
                    } catch (e) {}
                } else {
                    endLoading();
                }
            });
        } else {
            emit('submit', form.files);
            emit('groupIdChange', props.groupId);
        }
    } catch (error) {
        endLoading();
    }
};
const getFile = (data: any) => {
    form.files = data;
};
// 选择完地区后立即关闭
const orgChange = () => {
    cascaderRef.value.togglePopperVisible();
};
// 下载模板
const downTemplate = () => {
    if (apiText.value != '') {
        window.open(domain.BASE_API_URL + apiText.value);
    } else {
        window.open(domain.BASE_API_URL + '/scrm-api/console/media/text/download/template');
    }
};
const appDialog = reactive({
    visible: wordVisible,
    title: `${isEdit.value ? '编辑' : '新建'}话术`,
    width: '35%',
    cancel: cancelHandel,
    submit: submitHandel,
    cancelText: '取消',
    submitText: '保存'
});
// 上传模板验证
const checkExcel = (rule: any, value: any, callback: any) => {
    if (!value) callback(new Error('模板文件不能为空！'));
    callback();
};
const form = reactive({
    group: '',
    title: '',
    con: '',
    tags: [],
    files: '',
    tag_ids: []
});
const rules = reactive({
    title: {
        required: true,
        message: '文本标题不能为空',
        trigger: 'blur'
    },
    con: {
        required: true,
        message: '文本内容不能为空',
        trigger: 'blur'
    },
    files: {
        required: true,
        message: '模板文件不能为空',
        trigger: 'change'
    }
});
const fileInfo = reactive({
    type: 5,
    label: '',
    prop: 'files',
    uploadFileList: form.files,
    multiple: false,
    limitSize: 20,
    acceptFile: '.xls,.xlsx',
    uploadName: '上传模板'
});
const openTag = () => {
    wordSelectRef.value.showCreatTag = true;
    wordSelectRef.value.appDialog.visible = true;
    wordSelectRef.value.selectTags = form.tags;
};
// 获取标签
const getTags = (data: any) => {
    form.tags = data;
};
// 删除标签
const handleClose = (tag: string) => {
    const arr = form.tags.filter((item: any) => item.id != tag);
    form.tags = arr;
};
const onBeforeUpload = (file: any) => {
    const is2M = file.size / 1024 / 1024 <= 20;
    const types = ['.xls', '.xlsx'];
    if (!is2M) {
        ElMessage.warning(`上传的文件最大支持20M`);
        return false;
    }
    if (!types.includes(file.name.substring(file.name.lastIndexOf('.')))) {
        ElMessage.error('文件格式不正确！');
        return false;
    }
    return true;
};
const onHttpRequest = async ({ file }: any) => {
    form.files = file;
};

const onRemoveFile = () => {
    form.files = '';
};

watch(
    () => form.files,
    val => {
        formRef.value.validateField('files');
    }
);

watch(wordVisible, data => {
    if (data) {
        form.group = props.groupId;
        getGroupListFunc();
    }
});
watch(editInfo, editInfo => {
    form.group = editInfo.group_id;
    form.title = editInfo.title;
    form.con = editInfo.media_content_text_content;
    form.tags = editInfo.tagInfo;
    form.tag_ids = editInfo.tagInfo;
    editInfo.value = editInfo;
    setTimeout(() => {
        tagIdsRef.value?.init();
    }, 0);
});
defineExpose({
    isEdit,
    editInfo,
    wordVisible,
    isShowTag,
    apiText,
    appDialog
});
</script>
<style lang="scss" scoped>
.create-text {
    padding-top: 14px;
}

.radio_list {
    &_item {
        &_icon {
            width: 14px;
            height: 14px;
            margin: -3px 0 0 6px;

            img {
                margin-top: 2px;
                width: 100%;
                height: 100%;
                vertical-align: top;
            }
        }
    }

    :deep .el-radio__label {
        display: flex;
        align-items: center;
    }
}

.ml2 {
    margin-left: 2px;
}

.mr10 {
    margin-right: 10px;
}

.agree_ment {
    display: flex;
    align-items: center;
}

.zw_scroll {
    height: auto;
    margin-bottom: 16px;
}

.export {
    .el-form-item {
        margin-bottom: 0;
    }
}

.textWord {
    display: flex;
    margin-bottom: 12px;

    // align-items: center;
}

.file_info {
    margin-bottom: 12px;
    padding-left: 12px;
    display: flex;
    align-items: center;
    font-size: 14px;

    img {
        width: 20px;
        height: 20px;
    }

    .text {
        padding: 0 6px;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
    }

    .del_icon {
        cursor: pointer;
        margin-left: 5px;
    }
}

:deep(.el-form-item) {
    margin-bottom: 14px;

    .label_text {
        display: flex;
        align-items: center;
        gap: 6px;

        img {
            width: 14px;
            height: 14px;
        }
    }
}
</style>
